#include "borrowbook.h"
#include "ui_borrowbook.h"

BorrowBook::BorrowBook(QWidget *parent) :
    QMyPageWidget(parent),
    ui(new Ui::BorrowBook)
{
    ui->setupUi(this);
    db = DBOperation::getInstance();
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);  //选中整行
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//自适应对齐
    notify();

    ui->searchle->setStyleSheet("font: 25 14pt '微软雅黑 Light';" //字体
                                "color: rgb(31,31,31);"		//字体颜色
                                "padding-left:20px;"       //内边距-字体缩进
                                "background-color: rgb(255, 255, 255);" //背景颜色
                                "border:2px solid rgb(20,196,188);border-radius:15px;");

    ui->button_search->setStyleSheet(
                "QPushButton{"
                "color: rgb(0, 0, 0);"
                "border:2px groove gray;"
                "border-color: rgb(0, 0, 0);"
                "border-radius:10px;"
                "background-color: rgba(20,196,188, 210);"
                "font:28px '宋体';}"
                "QPushButton::hover{"
                "border:2px groove gray;"
                "border-color: rgb(255, 255, 255);"
                "background-color: rgba(251,102,102, 200);"
                "color:rgb(255,255,255);}"
                "QPushButton::pressed{"
                "color: rgb(255, 0, 0);"
                "border:2px groove gray;"
                "border-color: rgb(255, 0, 0);"
                "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(20,196,188, 210), stop:1 rgba(251,102,102, 200));}");


    ui->button_req->setStyleSheet(
                "QPushButton{"
                "color: rgb(0, 0, 0);"
                "border:2px groove gray;"
                "border-color: rgb(0, 0, 0);"
                "border-radius:10px;"
                "background-color: rgba(20,196,188, 210);"
                "font:28px '宋体';}"
                "QPushButton::hover{"
                "border:2px groove gray;"
                "border-color: rgb(255, 255, 255);"
                "background-color: rgba(251,102,102, 200);"
                "color:rgb(255,255,255);}"
                "QPushButton::pressed{"
                "color: rgb(255, 0, 0);"
                "border:2px groove gray;"
                "border-color: rgb(255, 0, 0);"
                "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(20,196,188, 210), stop:1 rgba(251,102,102, 200));}");


    ui->searchbox->setStyleSheet("QComboBox{color:rgb(0,0,0);"
                                 "background-color:rgba(20,196,188, 210);"
                                 "font-size:36px;"
                                 "padding: 1px 15px 1px 3px;"
                                 "border:2px solid rgb(0,0,0);"
                                 "border-radius:5px 5px 5px 5px;} "
                                 "QComboBox:hover{background-color:rgba(251,102,102, 200);}"
                                 );
}

BorrowBook::~BorrowBook()
{
    //db->close();
    delete ui;
}

void BorrowBook::notify()
{
    QSqlTableModel* model = new QSqlTableModel(nullptr, DBOperation::getDatabase());
    model->setTable("book_info");
    model->setFilter("");
    model->select();
    ui->tableView->setModel(model);

    QString headStr[] = {"ID", "书本名称", "类别", "作者", "价格", "语言", "出版日期", "库存数量"};
    for(int i=0; i < 8; i++)
    {
        model->setHeaderData(i, Qt::Horizontal, headStr[i]); // 设置表格 column 列名称
    }
    ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section {"
                                                     "color: brown;padding-left: 1px;border: 1px solid #6c6c6c;}");
}

void BorrowBook::on_button_search_clicked()
{

    QString index = ui->searchbox->currentText();
    QString content = ui->searchle->text();
    List_Book.clear();

    QString sql;


    if(index=="按ID"){
        index="bookCode";
    }else if(index=="按书名"){
        index = "bookName";
    }else if(index == "按类型"){
        index = "category";
    }else if(index == "按作者"){
        index = "author";
    }else if(index == "按价格"){
        index = "price";
    }else if(index == "按语言"){
        index = "language";
    }

    sql  = QString("(%0 like '%%1%')").arg(index, content);


    if(index == "按出版时间")
    {
        index = "publishDate";
        sql  = QString("%0='%1'").arg(index, content);
    }

    M = (QSqlTableModel*)ui->tableView->model();
    M->setFilter(sql);
    M->select();

}

void BorrowBook::showBookInfo()
{
    int row = ui->tableView->currentIndex().row();
    bookInfo = new BookInfoB(List_Book.at(row),row);
    connect(bookInfo,SIGNAL(signals_BookInfo(int)),this,SLOT(update_Book(int)));
    bookInfo->show();
}

void BorrowBook::update_Book(const int &index)
{
    Book temp = List_Book.at(index);
    temp.status = 1;
    List_Book.replace(index,temp);
}

void BorrowBook::on_button_req_clicked()
{
    QString sql;

    QSqlTableModel* lend_model = new QSqlTableModel(this, db->getDatabase());
    lend_model->setTable("lend_list");
    lend_model->setFilter(QString("readerNumber='%0'").arg(QRoleReader::getInstance()->getReader()));
    lend_model->select();
    // qDebug() << lend_model->lastError().text();

    QSqlTableModel* model = (QSqlTableModel*)ui->tableView->model();
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    //获取选择的所有行
    QList<QModelIndex> rows= ui->tableView->selectionModel()->selectedRows();

    QString books;
    //记录多行借阅书籍
    for(QModelIndex row : rows)
    {
        books += model->data(model->index(row.row(), 1)).toString() + "<br>";
    }
    if (QMessageBox::information(NULL,
                                 "提示",
                                 "是否借阅以下书籍!<br><br>" + books,
                                 QMessageBox::Yes | QMessageBox::No,
                                 QMessageBox::Yes
                                 ) == QMessageBox::No)return;

    //多行操作
    for(QModelIndex row : rows)
    {
        int nRow = row.row();
        //输出日志
        qDebug()
                << "user:" << QRoleReader::getInstance()->getUserName()
                << "row:" << nRow
                << "bookname:"
                << model->data(model->index(nRow, 1)).toString()
                << " num:"
                << model->data(model->index(nRow, 7)).toString();


        //获取书本数量
        books = model->data(model->index(nRow, 1)).toString();
        int nBookNumbers = model->data(model->index(nRow, 7)).toInt();
        int nBookCode = model->data(model->index(nRow, 0)).toInt();

        //判断书本数量是否可以借出
        if(nBookNumbers <= 0){
            QMessageBox(QMessageBox::Information, "提示", "《" + books + "》" + "书本不可借阅!").exec();
            continue;
        }

        //判断是否已借阅过书籍
        bool bReaded = false;
        for(int m = 0; m < lend_model->rowCount(); m++)
        {
            if (lend_model->record(m).value("bookName").toString().compare(books) == 0)
            {
                QMessageBox(QMessageBox::Information, "提示", "《" + books + "》" + "书本已经借阅!").exec();
                bReaded = true;
            }
        }
        if(bReaded)continue;

        //书本数量减一
        nBookNumbers--;
        sql = QString("UPDATE book_info SET num=%0 WHERE bookCode ='%1'").arg(nBookNumbers).arg(nBookCode);
        db->operate(sql);


        //插入借阅记录
        QDateTime curdate = QDateTime::currentDateTime();
        QDateTime dstdate = curdate;
        dstdate.setDate(curdate.date().addMonths(1));

        sql = QString("INSERT lend_list (bookname, readernumber, lendDate, backDate, backType) VALUES('%0', '%1', '%2', '%3', '%4')")
                .arg(model->data(model->index(nRow, 1)).toString())
                .arg(QRoleReader::getInstance()->getReader())
                .arg(curdate.toString("yyyy-MM-dd hh:mm:ss"))
                .arg(dstdate.toString("yyyy-MM-dd hh:mm:ss"))
                .arg("正常");
        db->operate(sql);
    }
    //刷新表项
    notify();

    QMessageBox(QMessageBox::Information, "提示", "借阅操作完成!").exec();
}
